import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index.vue'
import {getStore} from '@/controller/utils'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: "/",
    component: Index,
    redirect: "/index",
    children: [
      {
        path: "index",
        name: "Index",
        component: Index,
        meta: {
          requireAuth: true,
          title: '首页'
        }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

router.beforeEach((to, from, next) => {
  if(to.meta.title){
    document.title = to.meta.title
  }
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (getStore('username')) { // 判断本地是否存在token
      next()
    } else {
      // 未登录,跳转到登陆页面
      next({
        path: '/login'
      })
    }
  }else{
    next()
  }
});